package services

import (
	"errors"
	"im/app/conf"
	"im/app/models"
	"im/app/models/resonse/friends"
	"time"
)

type FriendsService struct {

}

/**
 * @op 通过用户id获取所有用户好友
 * @Params userId int 用户id
 **/
func (usg *FriendsService) GetUserFriendByUserId(userId int, page int, pageSize int) []*friends.ResFriendsList{
	res := []*friends.ResFriendsList{}
	user := &models.User{}
	pageVar := (page-1)*pageSize
	conf.Mdb.Table(user.TableName()+ " as u").
		Select("u1.id,u1.name,u1.created_at").
		Joins(" left join friends as f on f.user_id = u.id").
		Joins(" left join user as u1 on u1.id=f.user_fid").
		Where("u.id=?", userId).
		Limit(pageSize).
		Offset(pageVar).
		Scan(&res)

	return res
}

/**
 * @op 添加好友
 * @Params userId int 用户id
 * @Params friendId int 好友id
 **/
func (usg *FriendsService) AddFriend(userId int, friendId int) error {
	// 如果自己添加自己不行
	if userId == friendId {
		return errors.New("不能自己添加自己为好友")
	}
	tx := conf.Mdb.Begin()
	fu := models.Friends{
		UserId:    userId,
		UserFid:   friendId,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	// 先判断是否加入对方为好友
	f := models.Friends{}
	tx.Where("user_id=?",userId).Where("user_fid=?",friendId).Take(&f)
	if f.ID > 0 {
		tx.Rollback()
		return errors.New("已加入对方为好友")
	}
	ff := models.Friends{
		UserId:    friendId,
		UserFid:   userId,
		CreatedAt: time.Now().Unix(),
		UpdatedAt: time.Now().Unix(),
	}
	err := tx.Create(&fu).Error
	if err != nil {
		tx.Rollback()
		return  err
	}
	err = tx.Create(&ff).Error
	if err != nil {
		tx.Rollback()
		return  err
	}
	tx.Commit()

	return nil
}


/**
 * @op 添加好友
 * @Params userId int 用户id
 * @Params friendId int 好友id
 **/
func (usg *FriendsService) DeleteFriend(userId int, friendId int) error {
	tx := conf.Mdb.Begin()
	fu := models.Friends{}
	err := conf.Mdb.Where("user_id=?",userId).Where("user_fid=?",friendId).Delete(&fu).Error
	if err != nil {
		tx.Rollback()
		return  err
	}
	ff := models.Friends{}
	err = conf.Mdb.Where("user_id=?",friendId).Where("user_fid=?",userId).Delete(&ff).Error
	if err != nil {
		tx.Rollback()
		return  err
	}
	tx.Commit()

	return nil
}

/**
 * @op 获取好友信息
 * @Params userId int 用户id
 **/
func (usg *FriendsService) InfoFriend(userId int) *models.User {
	friend := models.User{}
	conf.Mdb.Where("id=?",userId).Select("id,name,sex,avatar,created_at").Take(&friend)

	return &friend
}

// 搜索好友
func (usg *FriendsService) SearchFriend(userName string, page int, pageSize int) []*models.User{
	res := []*models.User{}
	pageVar := (page-1)*pageSize
	conf.Mdb.Select("id,name,sex,avatar,created_at").
		Where("name like ?", userName + "%").
		Limit(pageSize).
		Offset(pageVar).
		Find(&res)

	return res
}